/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entity;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.*;
import javax.ejb.RemoveException;
import javax.naming.*;
import javax.sql.DataSource;
import transfer.Comment;
import transfer.Order;

/**
 *
 * @author Анна, Sergey
 */
public class Comments implements EntityBean {

    private DataSource dataSource;
    private EntityContext entityContext;
    private Comment comment = new Comment();
    
    public void setComment(Comment comment) {
        this.comment = comment;
    }
    
    public Comment getComment() {
        return comment;
    }
    
    public void setEntityContext(EntityContext entityContext) throws EJBException {
        try {
            this.entityContext = entityContext;
            Context context = new InitialContext();
            dataSource = (DataSource) context.lookup("jdbc/ossystem");
        } catch (NamingException ex) {
            throw new EJBException("Does not find jdbc/ossystem");
        }
    }

    public void unsetEntityContext() {
        entityContext = null;
    }
    
    public void ejbRemove() throws RemoveException, EJBException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "DELETE FROM Comments WHERE id_comments = ?");
            statement.setInt(1, comment.getIdComment().intValue());
            if (statement.executeUpdate() < 1) {
                throw new RemoveException("Deleting error. Can not remove comment");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection, statement);
        }
    }
    
    public void ejbActivate() {
    }
    
    public void ejbPassivate() {
    }
    
    public void ejbLoad() throws EJBException {
        Integer primaryKey = (Integer) entityContext.getPrimaryKey();
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_user, id_order, id_order_state, comment_text, comment_date "
                    + "FROM Comments WHERE id_comment = ?");
            statement.setInt(1, primaryKey.intValue());
            ResultSet resultSet = statement.executeQuery();
            if (!resultSet.next()) {
                throw new NoSuchEntityException("Comment with id = " + primaryKey + " not exists");
            }
            Context c = new InitialContext();
            comment = new Comment();
            if (resultSet.getInt(1) != 0) {
                UsersLocalHome userHome = (UsersLocalHome) c.lookup("java:comp/env/Users");
                UsersLocal userLocal = userHome.findByPrimaryKey(new Integer(resultSet.getInt(1)));
                comment.setUser(userLocal.getUser());
            } 
            OrdersLocalHome orderHome = (OrdersLocalHome) c.lookup("java:comp/env/Orders");
            OrdersLocal orderLocal = orderHome.findByPrimaryKey(new Integer(resultSet.getInt(2)));
            OrderStateLocalHome orderStateHome = (OrderStateLocalHome) c.lookup("java:comp/env/OrderState");
            OrderStateLocal orderStateLocal = orderStateHome.findByPrimaryKey(new Integer(resultSet.getInt(3)));
            comment.setOrder(orderLocal.getOrder());
            comment.setOrderState(orderStateLocal.getOrderState());
            comment.setCommentText(resultSet.getString(4));
            comment.setCommentDate(new java.util.Date(resultSet.getDate(5).getTime()));
            comment.setIdComment(primaryKey);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        } finally {
            closeConnection(connection, statement);
        }
    }
    
    public void ejbStore() throws EJBException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "UPDATE Comments SET id_user = ?, id_order = ?, id_order_state = ?, comment_text = ?, comment_date = ? "
                    + "WHERE id_comment = ?");
            if (comment.getUser() != null) {
                statement.setInt(1, comment.getUser().getIdUser().intValue());
            } else {
                statement.setNull(1, Types.INTEGER);
            }
            statement.setInt(2, comment.getOrder().getIdOrder().intValue());
            statement.setInt(3, comment.getOrderState().getIdOrderState().intValue());
            statement.setString(4, comment.getCommentText());
            statement.setDate(5, new Date(comment.getCommentDate().getTime()));
            statement.setInt(6, ((Integer) entityContext.getPrimaryKey()).intValue());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection, statement);
        }
    }
    
    public Collection ejbFindAllCommentsForOrder(Order order) throws FinderException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            ArrayList commects = new ArrayList();
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_comment "
                    + "FROM Comments WHERE id_order = ? ORDER BY comment_date DESC");
            statement.setInt(1, order.getIdOrder().intValue());
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Integer idOrder = new Integer(resultSet.getInt(1));
                commects.add(idOrder);
            }
            return commects;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection, statement);
        }
    }
    
    public java.lang.Integer ejbFindByPrimaryKey(Integer idComment) throws FinderException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_comments "
                    + "FROM Comments WHERE id_comments = ?");
            statement.setInt(1, idComment.intValue());
            ResultSet resultSet = statement.executeQuery();
            if (!resultSet.next()) {
                throw new FinderException("Comments with primary key " + idComment + " is not exists");
            }
            return new Integer(resultSet.getInt(1));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection, statement);
        }
    }
    
    public void ejbPostCreate(Comment acomment) throws CreateException {
    }
    
    public java.lang.Integer ejbCreate(Comment acomment) throws CreateException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            Statement stat = connection.createStatement();
            Integer idComment = null;
            ResultSet resultSet = stat.executeQuery("select seq.nextval from dual");
            if (resultSet.next()) {
                idComment = new Integer(resultSet.getInt(1));
            }
            stat.close();            
            comment.setIdComment(idComment);
            comment.setCommentDate(acomment.getCommentDate());
            comment.setCommentText(acomment.getCommentText());
            comment.setOrder(acomment.getOrder());
            comment.setOrderState(acomment.getOrderState());
            comment.setUser(acomment.getUser());
            statement = connection.prepareStatement("INSERT INTO Comments"
                    + "(id_comment, id_user, id_order, id_order_state, comment_text, comment_date) VALUES(?, ?, ?, ?, ?, ?)");
            statement.setInt(1, idComment.intValue());            
            if (acomment.getUser() != null) {
                statement.setInt(2, acomment.getUser().getIdUser().intValue());
            } else {
                statement.setNull(2, Types.INTEGER);
            }
            statement.setInt(3, acomment.getOrder().getIdOrder().intValue());
            statement.setInt(4, acomment.getOrderState().getIdOrderState().intValue());
            statement.setString(5, acomment.getCommentText());
            statement.setDate(6, new Date(acomment.getCommentDate().getTime()));
            if (statement.executeUpdate() != 1) {
                throw new CreateException("Inserted error");
            }
            return idComment;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection, statement);
        }
    }
    
    private void closeConnection(Connection connection, Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }    
}
